<template>

    <!--筛选条件-->
    <div class="shaixuan3">
        <el-row class="pt20">
            <el-col :span="12">
                <pers-button  size="medium " @click="add()" perms="live:lottery:add" type="primary" round label="新建抽奖"></pers-button>
            </el-col>
        </el-row>
        <div class="first_table">
            <el-table :data="tableData" style="width: 100%;margin-bottom: 20px;" row-key="id" border stripe default-expand-all v-loading="loading" >
                <el-table-column align="center" fixed  width="55" label="序号"  prop="id"></el-table-column>
                <el-table-column header-align="center" align="center" prop="title" label="奖品名称"></el-table-column>
                <el-table-column header-align="center" align="center" width="100"  label="图片">
                    <template slot-scope="scope">
                        <el-image :src="scope.row.im_url" fit="fill" style="width: 60px;height: 60px;"></el-image>
                    </template>
                </el-table-column>
                <el-table-column header-align="center" align="center" prop="number" label="奖品数量"></el-table-column>
                <el-table-column header-align="center" align="center" prop="countdown" label="活动时间(秒)"></el-table-column>
                <el-table-column header-align="center" align="center" prop="lott_state" label="开奖状态"></el-table-column>
                <el-table-column header-align="center" align="center" prop="ratat_count" label="预设中奖人员"></el-table-column>
                <el-table-column align="center" header-align="center" column-key="id" prop="id" label="操作">
                    <template slot-scope="scope" >
                        
                        <PersButton v-if="scope.row.status === 0" type="primary" size="medium"  perms="live:lottery:edit" label="编辑" @click="edit(scope.row)"></PersButton>
                        <PersButton v-if="scope.row.status === 0" type="primary" size="medium"  perms="live:lottery:launch" label="发起抽奖"  @click="choujiang(scope.row)" :class="{active:isActive}" ></PersButton>
                        <PersButton type="danger" size="medium" v-if="[1].includes(scope.row.status) " perms="live:lottery:end" label="结束抽奖" @click="finish(scope.row)" :class="{active1:isActive1}"></PersButton>
                        <couint-down v-if="scope.row.status === 1" :key="scope.row.id" :end-time="scope.row.room_time" @finish="handleCountDown(scope.row.id)" />
                        <PersButton v-if="scope.row.status === 3" type="text" perms="live:lottery:list" label="中奖名单" @click="handleDialogTableVisible(scope.row)"></PersButton>
                        <PersButton v-if="scope.row.status === 3 && scope.row.lott_state=='未开奖'" type="primary" perms="live:lottery:open" label="开奖" @click="editKaijiang(scope.row)" ></PersButton>

                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNumber" :page-sizes="[10, 50, 100, 200]" :page-size="pageSize" background layout="total, sizes, prev, pager, next, jumper" :total="total">
                </el-pagination>
            </div>
        </div>
        <el-dialog title="中奖名单" :visible.sync="dialogTableVisible" border style="width: 100%">
            <el-table :data="gridData" row-key="id" border style="width: 100%;"  >
                <el-table-column  align="center" prop="nickname" label="昵称" width="250"></el-table-column>
                <el-table-column  align="center" prop="types" label="是否真人" width="250"></el-table-column>
                <el-table-column  align="center" prop="phone" label="手机号" width="250"></el-table-column>
                <el-table-column  align="center" prop="nick_name" label="助教" width="400"></el-table-column>
                
            </el-table>
        </el-dialog>
        <el-dialog  title="开奖" :visible.sync="dialogFormKaijiang"  width="600px" append-to-body>
            <el-form :model="ruleForm" ref="ruleForm"  label-width="100px">
                    <el-form-item label="奖项名称" prop="title" >
                        <el-input v-model="ruleForm.title" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                
                    <el-form-item label="中奖人数" prop="number" >
                        <el-input v-model="ruleForm.number" autocomplete="off" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="领取方式" prop="darw_state">
                        <el-radio-group v-model="ruleForm.darw_state">
                            <el-radio :label="1">无</el-radio>
                        </el-radio-group>
                    </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormKaijiang = false">取 消</el-button>
                <el-button type="primary" @click=" subEditKaiJiangForm('ruleForm')" size="small" >开 奖</el-button>
            </div>
        </el-dialog>
        
        <el-dialog :visible.sync="open" width="600px" append-to-body :title="!form.id ? '新增抽奖/福袋' : '修改抽奖'">
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-row >
                    <el-col :span="18">
                        <el-form-item label="奖项名称" prop="title">
                            <el-input v-model="form.title" placeholder="请输入奖项名称" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="奖品图片" prop="im_url">
                            <div class="uploadcol">
                                <div class="uploadborder">
                                    <img v-if="form.im_url" :src="form.im_url" width="100%" height="100%" />
                                    <img v-else src="@/assets/img/uploadimg.jpg" width="100%" height="100%" />
                                </div>
                                <el-button type="primary" @click="openUploadDial()" size="mini"
                                           style="margin-top:10px">上传图片</el-button>
                            </div>
                        </el-form-item>
                    </el-col>
                    <el-col :span="13">
                        <el-form-item label="奖品数量" prop="number">
                            <el-input v-model="form.number" placeholder="奖品数量1-999"  />
                        </el-form-item>
                    </el-col>
                  
                    <el-col :span="15">
                        <el-form-item label="倒计时" prop="countdown" >
                            <el-select  v-model="form.countdown" placeholder="请选择" >
                                <el-option
                                    v-for="item in countdown"
                                    :key="item.value"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="15">
                        <el-form-item label="预设中奖" prop="pose_state">
                            <el-switch
                                v-model="form.pose_state"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :inactive-value="0"
                                :active-value="1"
                                  >
                            </el-switch>
                        </el-form-item>
                    </el-col>
                   
                    <el-col v-if="form.pose_state ==1" :span="25">
                        
                        <el-button type="text" @click="dialogFormVisible = true">在线用户</el-button>
                        <el-button type="text" @click="dialogFormBobot = true">机器人</el-button>
                    </el-col>
                  
                    <el-col :span="18">
                        <el-form-item label="中奖名单" prop="publish">
                            <el-switch
                                v-model="form.publish"
                                active-color="#13ce66"
                                inactive-color="#ff4949"
                                :active-value="1"
                                :inactive-value="0"
                                >
                            </el-switch>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="open = false" size="small">取 消</el-button>
                <el-button type="primary" @click="!form.id ? submitForm('form') : subEditForm('form')" size="small">确
                    定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="预设" :visible.sync="dialogFormVisible" width="800px" >
            <el-form :model="form" >
                <template>
                    <el-transfer
                        filterable
                        filter-placeholder="请输入用户名"
                        v-model="alluser"
                        :data="alldata">
                    </el-transfer>
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="预设" :visible.sync="dialogFormBobot" width="800px" >
            <el-form :model="form" >
                <template>
                    <el-transfer
                        filterable
                        filter-placeholder="请输入机器人"
                        v-model="alluser1"
                        :data="alldata1">
                    </el-transfer>
                </template>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormBobot = false">取 消</el-button>
                <el-button type="primary" @click="dialogFormBobot = false">确 定</el-button>
            </div>
        </el-dialog>
        <select-img :show="IsShowPicDig" @update="cleanDiaglog" :selectType="imgnum" @selectSure="selectImgs"
                    :type="0"></select-img>
        <select-img :show="IsShowPicDig1" @update="cleanDiaglog1" :selectType="imgnum1" @selectSure="lotteryImgs"
                    :type="0"></select-img>
    </div>
</template>

<script>
import PersButton from "@/components/PersButton.vue";
import CouintDown from "@/components/CountDown.vue";

import {
    getChouJiang,
    getChouJiangRobot,
    getChouJiangUser,
    getEditChouJiangRobot,
    getEditChouJiangUser,
    getPrizeList
} from '@/api/live/action';
import debounce from "@/common/debounce";
import {addLottery, addPrize, editPrize, finishPrize, getfinish, sendPrize} from "@/api/live/choujiang";
import SelectImg from "@/components/select-img.vue";

export default {
    components: {SelectImg, PersButton,CouintDown},
    props: {
        liveId: {
            type: String,
            default: ''
        },
        live_user_id: {
            type: String,
            default: ''
        },
        fliter: {
            type: String,
            default: ''
        },
        id: {
            type: String,
            default: ''
        },
        

    },
    data(){
        
        return {
            pageSize: 10, //一页显示多少条
            pageNumber: 1,
            total: 0, //总页数
            loading: false,
            open: false,
            state:'',
            input:'',
            gridData:[],
            isActive:false,
            isActive1:true,
            form:{
                title: "",
                im_url: "",
                number:"",
                countdown:"",
                pose_state:0,
                publish:1,
                alluser:[],
                alluser1:[],
                liveId:this.$props.liveId,
            },
            ruleForm:{
                link_url:"",
                darw_state:1,
                image:"",
            },
            formLabelWidth: '120px',
            tableData:[],
           
            rules:{
                title:[
                    { required: true, message: "奖项名称不能为空", trigger: "blur" }
                ],
                number:[{
                    required: true, message: "奖品数量不能为空", trigger: "blur"
                }
                ]
            },
           
            activeName: 'second',
            countdown:[
                {
                    value:'10',
                    label:'00:10'
                },{
                    value:'20',
                    label:'00:20'
                },{
                    value:'30',
                    label:'00:30'
                },{
                    value:'60',
                    label:'01:00'
                },{
                    value:'120',
                    label:'02:00'
                },{
                    value:'180',
                    label:'03:00'
                },{
                    value:'240',
                    label:'04:00'
                },{
                    value:'300',
                    label:'05:00'
                },{
                    value:'360',
                    label:'06:00'
                },{
                    value:'420',
                    label:'07:00'
                },{
                    value:'480',
                    label:'08:00'
                },{
                    value:'540',
                    label:'09:00'
                },{
                    value:'600',
                    label:'10:00'
                },{
                    value:'1800',
                    label:'30:00'
                },{
                    value:'3600',
                    label:'60:00'
                },
            ],
           
            IsShowPicDig: false,
            IsShowPicDig1: false,
            imgnum: 1, //选择图片数量,
            imgnum1: 1, //选择图片数量,
            dialogFormVisible:false,
            dialogFormBobot:false,
            dialogTableVisible: false,
            dialogFormKaijiang:false,
            value: [1],
            value4: [1],

            alldata: [
            ],
            alluser: [],
            alldata1: [],
            alluser1: [],

            showBtn:[],
        }
        
    },
    created(){
        this.init();
    },
   
    methods: {
        handleDialogTableVisible(row){
            getPrizeList({row}).then((res) => {
 
                if (res.code == 200) {
                    this.dialogTableVisible =true
                    this.gridData = res.data.list;
                    this.total = res.data.total;
                } else {
                    this.msgError(res.msg);
                }
            });
        },
       
        handleCountDown(data){
            let _param = {
                id: data
            }
            getfinish(_param).then((res) => {
                if (res.code == 200) {
                     this.showBtn.push(data.id)
                    this.init();
                } else {
                    this.msgError(res.msg);
                }
            });
        },
        init(){
            let _param = {
                input:this.input,
                state:this.state,
                liveId:this.$props.liveId,
                fliter:this.$props.fliter,
                user_id:this.$props.live_user_id,
                id:this.$props.id,
                pageSize:this.pageSize,
                pageNumber:this.pageNumber
            };
            getChouJiang(_param).then((res) => {
                
                if (res.code == 200) {
                    
                    this.tableData = res.data.list;
                    this.total = res.data.total;
                } else {
                    this.msgError(res.msg);
                }
            });
            
        },
        handleClick(tab, event) {
            console.log(tab, event);
        },
        add: async function () {
           const res  = await  getChouJiangUser({liveId:this.liveId})
            const {data}  = await  getChouJiangRobot({liveId:this.liveId})
            this.alldata = res.data.map(item=>{
                item.key = item.id
                return item
            })
            this.alldata1 = data.map(item=>{
                item.key = item.id
                return item
            })
            this.form = {
                title: "",
                im_url: "",
                number:"",
                publish:'1',
                countdown:"",
                pose_state:'0',
                alluser:[],
                alluser1:[],
                liveId:this.$props.liveId
              
            };

            this.open = true;
        },
        //添加抽奖
        submitForm: function (data) {
            this.submitLoading = true;
            debounce(() => {
                this.$refs[data].validate((valid) => {
                    if (valid) {
                        if(this.form.pose_state==1){
                            if(this.alluser.length+this.alluser1.length<=0){
                                this.$message.error('您已打开预设中奖,未选择在线用户或者机器人');
                                return false;
                            }else{
                                if(this.alluser.length+this.alluser1.length!=this.form.number){
                                    this.$message.error('预设中奖,在线用户或者机器人的总数量必须等于奖品数量');
                                    return false;
                                }
                            }
                            this.form.alluser = this.alluser
                            this.form.alluser1 = this.alluser1
                        }
                        addPrize(this.form).then((res) => {
                            this.submitLoading = false;
                            console.log(res)
                            if (res.code == 200) {
                                this.msgSuccess(res.msg);
                                this.init();
                                this.open = false;
                                this.copy_open = false;
                                this.submitLoading = false;

                            } else {
                                this.msgError(res.msg);

                                this.submitLoading = false;
                            }
                        })
                    } else {
                        this.submitLoading = false;
                        return false;
                    }
                })
            }, 500);

        },
        //编辑抽奖
        subEditForm: function (data) {
            this.submitLoading = true;
            debounce(() => {
                if(this.form.pose_state==1){
                    if(this.alluser.length+this.alluser1.length<=0){
                        this.$message.error('您已打开预设中奖,未选择在线用户或者机器人');
                        return false;
                    }else{
                        if(this.alluser.length+this.alluser1.length!=this.form.number){
                            this.$message.error('预设中奖,在线用户或者机器人的总数量必须等于奖品数量');
                            return false;
                        }
                    }
                    this.form.alluser = this.alluser
                    this.form.alluser1 = this.alluser1
                }
                this.$refs[data].validate((valid) => {
                    if (valid) {
                        editPrize(this.form).then((res) => {
                            this.submitLoading = false;
                            console.log(res)
                            if (res.code == 200) {
                                this.msgSuccess(res.msg);
                                this.init();
                                this.open = false;
                                this.copy_open = false;
                                this.submitLoading = false;
                            } else {
                                this.msgError(res.msg);

                                this.submitLoading = false;
                            }
                        })
                    } else {
                        this.submitLoading = false;
                        return false;
                    }
                })
            }, 500);
        },
        //开奖
        subEditKaiJiangForm: function (data) {
            debounce(() => {
                this.$refs[data].validate((valid) => {
                    if (valid) {
                        addLottery(this.ruleForm).then((row) => {
                            if (row.code == 200) {
                              
                                this.msgSuccess(row.msg);
                                this.$emit('lotteryMsg',row)
                                this.init();
                                this.dialogFormKaijiang = false;
                            } else {
                                this.msgError(row.msg);
                            }
                        })
                        
                    } else {
                        return false;
                    }
                })
            }, 500);

        },
      
        edit:async function (editData) {
            this.form = {...editData};

            const res  = await  getChouJiangUser({liveId:this.liveId})
            const {data}  = await  getChouJiangRobot({liveId:this.liveId})
            this.alldata = res.data.map(item=>{
                item.key = item.id
                return item
            })
            this.alldata1 = data.map(item=>{
                item.key = item.id
                return item
            })

           const res1  = await  getEditChouJiangUser(editData)
           const data1  = await  getEditChouJiangRobot(editData)

            let selectedArr = []
            let selectedArr1 = []
            if(res1.data.length>0){
                selectedArr = res1.data.map(item=>{
                 return   item.id
                })
            }
            if(data1.data.length>0){
                selectedArr1 = data1.data.map(item=>{
                    return   item.id
                })
            }
            this.alluser1 = [...selectedArr1]
            this.alluser =[...selectedArr]
            
            this.$props.liveId
            this.open = true;
            
        },
        editKaijiang: function(data){
            this.ruleForm = {...data};
            this.$props.liveId
            this.dialogFormKaijiang = true;
            
        },
        //发起抽奖
        choujiang: function (data) {
            this.$confirm('确定要发起抽奖吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let _param = {
                    liveId:this.$props.liveId,
                    id: data.id
                }
                sendPrize(_param).then((row) => {
                    if (row.code == 200) {
                        this.init();
                        this.msgSuccess(row.msg);
                        this.$emit('choujiang',row)
                    } else {
                        this.msgError(row.msg);
                    }
                })
         
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        //手动结束抽奖
        finish: function (data) {
            this.$confirm('确定要结束吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                let _param = {
                    liveId:this.$props.liveId,
                    id: data.id
                }
                finishPrize(_param).then((row) => {
                    if (row.code == 200) {
                        this.init();
                        this.msgSuccess(row.msg);
                        this.$emit('finish',row)
                        
                    } else {
                        this.msgError(row.msg);
                    }
                })

            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });
            });
        },
        handleSizeChange: function (e) {
            console.log(e);
            this.pageSize = e;
            this.init();
        },
        handleCurrentChange: function (e) {
            console.log(e);
            this.pageNumber = e;
            this.init();
        },
        cleanDiaglog: function (shows) {
            this.IsShowPicDig = false;
        },
        cleanDiaglog1: function (shows) {
            this.IsShowPicDig1 = false;
        },
        openUploadDial: function () {
            this.IsShowPicDig = true;
        },
        openUploadDial1: function () {
            this.IsShowPicDig1 = true;
        },
        selectImgs: function (res) {

            console.log(res);
            this.IsShowPicDig = true;
            this.form.im_url = res[0].urls
        },
        lotteryImgs: function (res) {

            console.log(res);
            this.IsShowPicDig1 = true;
            this.ruleForm.image = res[0].urls
        },
        search(e){
            this.init();
        },
        statechange(e){
            this.init();
        },

    }

}

</script>


<style>
.active{
    display: none;
}
.active1{
    display: none;
}

.transfer-footer {
    margin-left: 20px;
    padding: 6px 5px;
}
.shaixuan{
    width: 100%;
}

.yixuan {
    margin: 20px;
    color: #787878;
}

.first_table{
    margin-top: 20px;
}



.groupmenu .el-tree-node__children .el-tree-node__children .el-tree-node__children .el-tree-node__content {
    float: left;
    width: 100px;
}
.icon-body .el-dialog__body{
    max-height: 500px;
    overflow: auto;
}

</style>